<template>
  <view class="root">
    <!-- 活动标题 -->
    <view class="form-item">
      <p class="label">活动标题</p>
      <input class="input" v-model="title" type="text" placeholder="请输入活动标题" />
    </view>

    <!-- 活动内容 -->
    <view class="form-item">
      <p class="label">活动内容</p>
      <textarea class="textarea" v-model="content" placeholder="请输入活动内容"></textarea>
    </view>

    <!-- 图片上传 -->
    <view class="form-item">
      <p class="label">上传图片</p>
      <uni-file-picker
        fileMediatype="image"
        mode="grid"
        :limit="9"
        :imageStyles="{ width: 100, height: 100, borderRadius: 8 }"
        @select="onSelect"
      ></uni-file-picker>
    </view>

    <!-- 发布按钮 -->
    <view class="button" @click="publish">发布</view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { getToken } from '@/utils/auth'; // 获取 token 方法

const title = ref('');
const content = ref('');
const fileList = ref([]); // 存储选中的文件
const parentId = ref(null); // parentId 初始化为 null，避免类型不匹配
const activityImageId = ref(null); // 用于存储活动的 imageId

// **选择文件**
const onSelect = (res) => {
  fileList.value = res.tempFiles.map(file => ({
    name: file.name,
    path: file.path,
  }));
};

// **逐张上传图片**
const uploadImages = async () => {
  if (fileList.value.length === 0) {
    uni.showToast({ title: '请先选择图片', icon: 'none' });
    return null;
  }
  const uploadedImages = [];
  const token = getToken();
  
  for (let i = 0; i < fileList.value.length; i++) {
    const file = fileList.value[i];
    try {
      const res = await new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'http://localhost:8866/sn/images/upload', // 后端上传接口
          filePath: file.path, // 逐张上传
          name: 'files',
          formData: {
            parentId: parentId.value !== null ? parentId.value : '',  // 确保传递正确值
          },
          header: {
            Authorization: token,
          },
          success: (uploadRes) => resolve(JSON.parse(uploadRes.data)),
          fail: (err) => reject(err),
        });
      });

      if (res.code === 200) {
        if (i === 0) {
          // 上传第一张图片时，保存返回的 imageId 作为活动 imageId 和 parentId
          activityImageId.value = res.data[0].imageId; // 保存活动的 imageId
          parentId.value = res.data[0].imageId; // 后续图片的 parentId 设为活动的 imageId
          console.log('更新的 activityImageId:', activityImageId.value); // 打印调试信息
        } else {
          // 后续图片使用已有的 parentId
          res.data.forEach(img => img.parentId = parentId.value);
        }

        uploadedImages.push(...res.data); // 将当前上传的图片加入列表
      } else {
        uni.showToast({ title: '上传失败', icon: 'none' });
        return null;
      }
    } catch (error) {
      console.error('上传失败:', error);
      uni.showToast({ title: '上传失败，请检查网络', icon: 'none' });
      return null;
    }
  }

  return uploadedImages;
};

// **发布活动**
const publish = async () => {
  const uploadedImages = await uploadImages();
  if (!uploadedImages) return;

  const activityData = {
    title: title.value,
    content: content.value,
    images: uploadedImages,
    imageId: activityImageId.value, // 将活动的 imageId 加入数据
  };

  const token = getToken();

  try {
    const res = await uni.request({
      url: 'http://localhost:8866/sn/activities/add',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        Authorization: token,
      },
      data: activityData,
    });

    if (res.data.code === 200) {
      uni.showToast({ title: '活动发布成功', icon: 'success' });
      uni.navigateBack();
    } else {
      uni.showToast({ title: '活动发布失败', icon: 'none' });
    }
  } catch (error) {
    uni.showToast({ title: '网络错误', icon: 'none' });
  }
};
</script>

<style>
.root {
  padding: 20px;
  background-color: #f9f9f9;
  height: 100vh;
}

.form-item {
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.input,
.textarea {
  width: 100%;
  padding: 10px;
  font-size: 14px;
  border-radius: 8px;
  border: 1px solid #ddd;
  background-color: #fff;
}

.textarea {
  height: 100px;
  resize: none;
}

.button {
  width: 100%;
  padding: 14px;
  font-size: 18px;
  background-color: #007aff;
  color: white;
  border-radius: 30px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.button:hover {
  background-color: #005bb5;
}
</style>
